package leetCode;

import cn.hutool.core.lang.Console;

import java.util.HashMap;

public class MinimumWindowSubstring {
    public static void main(String[] args) {
        String s = "ADOBECODEBANC";
        String t = "ABC";
        Console.log(minimumWindowSubstring(s, t));
    }

    private static String minimumWindowSubstring(String s, String t) {
        HashMap<Character, Integer> map1 = new HashMap<>();
        HashMap<Character, Integer> map2 = new HashMap<>();
        for (int i = 0; i < t.length(); i++) {
            map2.put(t.charAt(i), map2.getOrDefault(t.charAt(i), 0) + 1);
        }
        String ans = "";
        int len = 0x3f3f3f3f, cnt = 0;  //有多少个元素符合
        for (int i = 0, j = 0; i < s.length(); i++) {
            map1.put(s.charAt(i), map1.getOrDefault(s.charAt(i), 0) + 1);
            if (map2.containsKey(s.charAt(i)) && map1.get(s.charAt(i)) <= map2.get(s.charAt(i))) cnt++;
            while (j < i && (!map2.containsKey(s.charAt(j)) || map1.get(s.charAt(j)) > map2.get(s.charAt(j)))) {
                int count = map1.get(s.charAt(j)) - 1;
                map1.put(s.charAt(j), count);
                j++;
            }
            if (cnt == t.length() && i - j + 1 < len) {
                len = i - j + 1;
                ans = s.substring(j, i + 1);
            }
        }
        return ans;
    }
}
